package com.wei.strategy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.ehcache.core.util.CollectionUtil;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.AbstractCellWriteHandler;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.wei.excelmodel.CellStyleModel;

@SuppressWarnings("deprecation")
public class CustomCellStyleHandler extends AbstractCellWriteHandler {

	/**
	 * 用于存储单元格样式对象 将 CellStyle 缓存下来，防止导出：超过创建超过6W个CellStyle对象报错
	 */
	private Map<String, CellStyle> contentCellStyleCache = new HashMap<String, CellStyle>();

	/**
	 * 缓存的 单元格样式对象 的KEY
	 */
	public final static String CELL_STYLE_CACHE_KEY = "CELL_STYLE_CACHE_KEY";

	/**
	 * 每 ROW_PARAM 行设置背景色
	 */
	public final static int ROW_PARAM = 2;

	@Override
	public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
			List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
		if (!isHead) {
			// 除头外，每两行设置背景色
			if ((relativeRowIndex + 1) % ROW_PARAM == 0) {
				CellStyle cellStyle = contentCellStyleCache.get(CELL_STYLE_CACHE_KEY);
				if (ObjectUtils.isEmpty(cellStyle)) {
					Workbook workbook = writeSheetHolder.getParentWriteWorkbookHolder().getWorkbook();
					cellStyle = workbook.createCellStyle();
					contentCellStyleCache.put(CELL_STYLE_CACHE_KEY, cellStyle);
				}
				cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
				cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
				cellStyle.setAlignment(HorizontalAlignment.CENTER);
				cell.setCellStyle(cellStyle);
			}
		}
	}

}